package com.example.demo.util;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 统一响应结果类
 */
@Data
@NoArgsConstructor // 空参构造器
@AllArgsConstructor // 全参构造器
public class Result<T> {
    private Integer code;
    private String msg;
    private T data;
    // 给一个时间戳
    private long time;

    // 手动添加一个枚举类型的set方法
    // 作用：通过一个枚举对象对Result的两个属性赋值
    public void setResultCode(ResultCode resultCode){
        this.setCode(resultCode.getCode());
        this.setMsg(resultCode.getMsg());
    }

    // 通过一些静态方法，让Result可以返回自己的对象
    // 成功后返回数据
    public static Result success(Object data){
        Result success = success();
        success.setData(data);
        return success;
    }
    // 成功后不返回数据
    public static Result success(){
        Result result = new Result();
        result.time = System.currentTimeMillis();
        result.setResultCode(ResultCode.SUCCESS);
        return result;
    }

    // 失败不带数据
    public static Result failure(ResultCode resultCode){
        Result result = new Result();
        result.time = System.currentTimeMillis();
        result.setResultCode(resultCode);
        return result;
    }
    // 失败带数据
    public static Result failure(ResultCode resultCode,Object data){
        Result failure = failure(resultCode);
        failure.setData(data);
        return failure;
    }

    // 自定义类型的失败
    public static Result action(Integer code,String msg){
        Result result = new Result();
        result.time = System.currentTimeMillis();
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }
}
